<template>
  <app-dialog-form
    :title="`${props.content && props.content !== '' ? '修改' : ''}回复内容`"
    :confirm="handleSubmit"
    width="600px"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="form"
      :inline="true"
      :model="formData"
      :rules="formRules"
      label-width="0px"
      size="large"
    >
      <el-form-item
        prop="content"
      >
        <el-input
          class="reply-text-input"
          type="textarea"
          :rows="4"
          placeholder="请输入回复内容"
          v-model="formData.content"
        />
      </el-form-item>
    </el-form>
  </app-dialog-form>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { IElForm, IFormRule } from '@/types/element-plus'
import { ElMessage } from 'element-plus'
import type { ReplyForm } from '@/api/types/product'
import { replyCommentById } from '@/api/product'

const props = defineProps({
  content: {
    type: String,
    default: ''
  },
  replyId: {
    type: Number,
    required: true
  }
})

interface EmitsType {
  (e: 'update:reply-id', value: number): void
  (e: 'success'): void
}

const emit = defineEmits<EmitsType>()

const formLoading = ref(false)
const form = ref<IElForm | null>(null)
const formData = ref<ReplyForm>({
  content: ''
})

const formRules = ref<IFormRule>({
  content: [
    { required: true, message: '请输入回复内容', trigger: 'blur' }
  ]
})

const handleDialogOpen = () => {
  formLoading.value = true
  formData.value.content = props.content
  formLoading.value = false
}

const handleDialogClosed = () => {
  emit('update:reply-id', 0)
  form.value?.clearValidate() // 清除验证结果
  form.value?.resetFields() // 清除表单数据
}

const handleSubmit = async () => {
  const valid = await form.value?.validate()
  if (!valid) {
    return
  }
  await replyCommentById(props.replyId, formData.value.content)
  formData.value.content = ''
  emit('success')
  ElMessage.success('回复成功')
}

</script>

<style lang="scss" scoped>
.el-form-item {
  width: 100%;
}
.reply-text-input {
  display: inline-block;
  width: 100%;
  position: relative;
  vertical-align: middle;
  line-height: normal;
}
</style>
